import { sendAddClient } from "../../../network/client";
import { debounce,toast, throttle } from '../../../utils/Tools'

// pages/client/client-add/client-add.js
Page({
  data: {
    clientWay:'1',
    contacts:[
      {name:'',position:'',phone:'',status:'add'}
    ]
  },
  onLoad: function (options) {
    this.handleContactInput = debounce(this.handleContactInput)
    this.formSubmit = throttle(this.formSubmit,3000)
  },
  handleRadio(e){ //处理单选框选择
    this.setData({
      clientWay: e.detail
    });
  },
  handleAddContacts(e){ //   处理点击添加联系人
    const {status,index} = e.currentTarget.dataset
    switch(status){
      case 'add':
        if(this.data.contacts.length<2){
          this.setData({
            contacts:this.data.contacts.concat({name:'',position:'',phone:'',status:'close'})
          })
        }
        break;
      case 'close':
        this.data.contacts.splice(index,1);
        this.setData({contacts:this.data.contacts})
        break;
    }
  },
  handleContactInput(e){
    const {index,box} = e.currentTarget.dataset
    const value = `contacts[${index}].${box}`
    this.setData({
      [value]: e.detail.value
    })
  },
  formSubmit(e){  //   处理确认添加
    const {clientAddress,clientName,clientType,telephone} = e.detail.value
    const data = {
      clientAddress,
      clientName,
      clientType,
      telephone,
      contacts: JSON.stringify(this.data.contacts)
    }
    if(data.clientAddress&&data.clientName&&data.telephone){
      sendAddClient(data).then(res=>{
        if(res.code === 200){
          toast('添加成功','success')
          wx.switchTab({
            url: '/pages/client/client/client'
          });
        }else{
          toast(res.msg)
        }
      })
    }else{
      toast('请注意不要留空')
    }
  }
})